package com.hq.stat.controller;

import cn.hutool.core.date.DateUtil;
import com.hq.bus.domain.Customer;
import com.hq.bus.domain.Rent;
import com.hq.bus.service.CustomerService;
import com.hq.bus.service.RentService;
import com.hq.stat.domain.BaseEntity;
import com.hq.stat.service.impl.StatService;
import com.hq.sys.util.ExportRentUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsPackage: com.hq.stat.controller
 * @Author: jiangjunjie
 * @CreateTime: 2024-12-18  14:09
 * @Description: TODO
 * @Version: 1.8
 */
@Controller
@RequestMapping("stat")
public class StatController {
    @Autowired
    private RentService rentService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private StatService statService;

    // 导出出租单统计报excel表
    @GetMapping("/exportRent")
    public ResponseEntity<Object> exportRent(String rentid) throws IOException {
        // 获取指定ID的出租记录
        Rent rent = rentService.queryRentByIdentity(rentid);
        if (rent == null) {
            throw new IllegalArgumentException("出租单不存在");
        }
        //根据身份证号查找客户
        Customer customer = customerService.queryCustomerByIdentity(rent.getIdentity());
        if (customer == null) {
            throw new IllegalArgumentException("客户不存在");
        }
        String filename = customer.getCustname() + "出租表单.xls";
        String sheetName = customer.getCustname() + "出租单";

        ByteArrayOutputStream bos = ExportRentUtils.exportRent(rent, customer, sheetName);
        try{
            //处理文件名乱码
            filename= URLEncoder.encode(filename,"UTf-8");
            //创建封装相应头信息的对象
            HttpHeaders headers = new HttpHeaders();
            //封装网应内容类型(APPLICATION_0CTETSTREAM应的内容不限定)
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //读是下我的文件的各称
            headers.setContentDispositionFormData("attachment",filename);
            return new ResponseEntity<Object>(bos.toByteArray() ,headers, HttpStatus.CREATED);
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return null;
    }

    //导出所有出租单
    @GetMapping("/exportAllRents")
    public ResponseEntity<Object> exportAllRent() throws IOException {
        List<Rent> rentList = rentService.queryAllRents();
        //创建工作表
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        Sheet sheet = hssfWorkbook.createSheet("出租表单");
        //创建表头
        sheet.createRow(0).createCell(0).setCellValue("出租单号");
        sheet.getRow(0).createCell(1).setCellValue("身份证");
        sheet.getRow(0).createCell(2).setCellValue("车牌号");
        sheet.getRow(0).createCell(3).setCellValue("出租价格");
        sheet.getRow(0).createCell(4).setCellValue("归还状态");
        sheet.getRow(0).createCell(5).setCellValue("出租开始时间");
        sheet.getRow(0).createCell(6).setCellValue("出租结束时间");
        sheet.getRow(0).createCell(7).setCellValue("操作员");
        sheet.getRow(0).createCell(8).setCellValue("录入时间");
        int rowIndex = 1; // 从第1行开始写入数据
        for (Rent rent : rentList) {
            Row row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(rent.getRentid());
            row.createCell(1).setCellValue(rent.getIdentity());
            row.createCell(2).setCellValue(rent.getCarnumber());
            row.createCell(3).setCellValue(rent.getPrice());
            //出租状态 1 出租 0 归还
            if (rent.getRentflag() == 1) {
                row.createCell(4).setCellValue("出租");
            } else {
                row.createCell(4).setCellValue("归还");
            }
            //格式化时间
            row.createCell(5).setCellValue(DateUtil.format(rent.getBegindate(), "yyyy-MM-dd HH:mm:ss"));
            row.createCell(6).setCellValue(DateUtil.format(rent.getReturndate(), "yyyy-MM-dd HH:mm:ss"));
            row.createCell(7).setCellValue(rent.getOpername());
            row.createCell(8).setCellValue(DateUtil.format(rent.getCreatetime(), "yyyy-MM-dd HH:mm:ss"));
        }
        // 自动调整列宽
        for (int i = 0; i < 8; i++) {
            sheet.autoSizeColumn(i);
        }



        // 处理文件名乱码
        String filename = "所有出租单.xls";
        filename = URLEncoder.encode(filename, "UTF-8");

        // 创建封装响应头信息的对象
        HttpHeaders headers = new HttpHeaders();
        // 封装响应内容类型
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 设置下载附件的方式以及文件名
        headers.setContentDispositionFormData("attachment", filename);
        hssfWorkbook.close();
        // 将工作簿写入字节数组输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        hssfWorkbook.write(bos);

        return new ResponseEntity<>(bos.toByteArray(), headers, HttpStatus.OK);
    }
    /**
     * 加载客户地区数据
     * @return
     */
    @RequestMapping("loadCustomerAreaStatJson")
    @ResponseBody
    public List<BaseEntity> loadCustomerAreaStatJson(){
        return this.statService.loadCustomerAreaStatList();
    }
    //加载公司年度月份统计数据
    @RequestMapping("loadCompanyYearGradeStatJson")
    @ResponseBody
    public List<Double> loadCompanyYearGradeStatJson(String year){
        List<Double> entities =
                this.statService.loadCompanyYearGradeStatList(year);
        for (int i = 0; i < entities.size(); i++) {
            if (null == entities.get(i)) {
                entities.set(i, 0.0);
            }
        }
        return entities;
    }
    //加载业务员年度月份统计数据
    @RequestMapping("loadOpernameYearGradeStatJson")
    @ResponseBody
    public Map<String, Object> loadOpernameYearGradeStatJson(String year) {
        List<BaseEntity> entities = this.statService.loadOpernameYearGradeStatList(year);
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> names = new ArrayList<String>();
        List<Double> values = new ArrayList<Double>();
        for (BaseEntity baseEntity : entities) {
            names.add(baseEntity.getName());
            values.add(baseEntity.getValue());
        }
        map.put("name", names);
        map.put("value", values);
        return map;
    }

}




